const SECONDS = 1000
const MINUTES = 60 * SECONDS
const HOURS = 60 * MINUTES
const DAY = 24 * HOURS
const MONTH = 30 * DAY // 一月当作30天
const YEAR = 12 * MONTH + 5 // 一年当作有365天
/**
 * 时间归零
 * @param date
 * @returns
 */
export const toZero = (date = new Date()) => {
  const newDate = new Date(date)
  const zeroDate = new Date(0)
  zeroDate.setFullYear(newDate.getFullYear())
  zeroDate.setMonth(newDate.getMonth())
  zeroDate.setDate(newDate.getDate())
  return zeroDate
}

/**
 * 获取周一
 * @param date
 * @returns
 */
export const getFirstDayOfWeek = (date = new Date()) => {
  const newDate = new Date(date)
  //获取星期几，即weekday的值为1-7
  const weekday = newDate.getDay() || 7
  newDate.setDate(newDate.getDate() - weekday + 1) //往前算（weekday-1）天，年份、月份会自动变化
  return toZero(newDate)
}

/**
 * 获取月第一天
 * @param date
 * @returns
 */
export const getFirstDayOfMonth = (date = new Date()) => {
  const newDate = new Date(date)
  newDate.setDate(1)
  return toZero(newDate)
}

/**
 * 获取年第一天
 * @param date
 * @returns
 */
export const getFirstDayOfYear = (date = new Date()) => {
  const newDate = new Date(date)
  newDate.setDate(1)
  newDate.setMonth(0)
  return toZero(newDate)
}

/**
 * 两日期的差值
 * @param date 减去日期
 * @param defaultDate 被减日期
 * @param accuracy 精度
 */
export const differTo = (
  date = new Date(),
  defaultDate = new Date(),
  accuracy = 'yyyy'
) => {
  const dateFormat = new Date(date)
  const defaultDateFormat = new Date(defaultDate)
  const timeStamp = defaultDateFormat.getTime() - dateFormat.getTime()

  const dateModel = {
    yyyy: 0,
    MM: 0,
    dd: 0,
    HH: 0,
    mm: 0,
    ss: 0
  }
  const remainder = {
    yyyy: 0,
    MM: 0,
    dd: 0,
    HH: 0,
    mm: 0,
    ss: 0
  }
  const defaultModel = {
    yyyy: YEAR,
    MM: MONTH,
    dd: DAY,
    HH: HOURS,
    mm: MINUTES,
    ss: SECONDS
  }

  // 找出精度所在位置
  const index = Object.keys(dateModel).findIndex((it) => it === accuracy)

  // 临时时间戳
  let tempStamp = timeStamp
  Object.keys(remainder).forEach((it, i) => {
    // 如果大于等于所在下标则开始指向
    if (i >= index) {
      tempStamp = tempStamp % defaultModel[it]
      remainder[it] = tempStamp
    }
  })

  tempStamp = timeStamp
  Object.keys(dateModel).forEach((it, i) => {
    if (i >= index) {
      dateModel[it] = Math.floor(
        tempStamp / defaultModel[it]
      )
      tempStamp = remainder[it]
    }
  })

  return Object.assign({ timeStamp }, dateModel)
}

export const getDifferString = (date, defaultDate) => {
  if(!defaultDate){
    return '--'
  }
  const differDate = differTo(date, defaultDate)
  let str = differDate.yyyy ? differDate.yyyy + '年' : ''
  str += differDate.MM ? differDate.MM + '月' : ''
  str += differDate.dd ? differDate.dd + '天' : ''
  str += differDate.HH ? differDate.HH + '小时' : ''
  str += differDate.mm ? differDate.mm + '分钟' : ''
  str += differDate.ss ? differDate.ss + '秒' : ''
  return str
}
